package com.icesoft.system.service.impl;

import com.icesoft.framework.core.service.impl.BaseServiceImpl;
import com.icesoft.system.entity.Account;
import com.icesoft.system.entity.BaseLoginUser;
import com.icesoft.system.mapper.AccountMapper;
import com.icesoft.system.service.AccountService;
import com.icesoft.system.types.AuthTypeDictionary;
import com.icesoft.system.types.SystemSettingTypeDictionary;
import com.icesoft.system.util.PasswordUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class AccountServiceImpl extends BaseServiceImpl<AccountMapper, Account> implements AccountService {

	private final AuthTypeDictionary authTypeDictionary;

	private final SystemSettingTypeDictionary systemSettingTypeDictionary;

	@Override
	public Account findByUsername(String username) {
		return lambdaQuery().eq(Account::getAuthAccount, username).one();
	}

	public void createSystemEntity(BaseLoginUser dto, String username) {
		Account account = new Account();
		account.setUserId(dto.getId());
		account.setUserType(dto.getUserType());
		account.setAuthAccount(username);
		account.setSecretSalt("icesoft-account");
		account.setAuthSecret(PasswordUtil.md5(systemSettingTypeDictionary.getDefaultPassword() + account.getSecretSalt()));
		account.setAuthType(authTypeDictionary.getAccount());
		createEntity(account);

		if (dto.getPhone() != null) {
			Account phone = new Account();
			phone.setUserId(dto.getId());
			phone.setUserType(dto.getUserType());
			phone.setAuthAccount(dto.getPhone());
			phone.setSecretSalt("icesoft-phone");
			phone.setAuthSecret(PasswordUtil.md5(systemSettingTypeDictionary.getDefaultPassword() + phone.getSecretSalt()));
			phone.setAuthType(authTypeDictionary.getPhone());
			createEntity(phone);
		}

		if (dto.getEmail() != null) {
			Account email = new Account();
			email.setUserId(dto.getId());
			email.setUserType(dto.getUserType());
			email.setSecretSalt("icesoft-email");
			email.setAuthAccount(dto.getEmail());
			email.setAuthSecret(PasswordUtil.md5(systemSettingTypeDictionary.getDefaultPassword() + email.getSecretSalt()));
			email.setAuthType(authTypeDictionary.getEmail());
			createEntity(email);
		}
	}

}
